package com.zy.controller;

import com.zy.dto.UserPointsReq;
import com.zy.dto.UserRanking;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @Author zy
 * @Date 2025/02/14
 * @Desc
 * @Version 1.0
 */
@RestController
public class RankingListController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private static final String userKey = "user:book";

    @PostMapping("/addUserPoint")
    public boolean addUserPoint(@RequestBody List<UserPointsReq> userPointsReqList) {
        //遍历userPointsReqList
        for (UserPointsReq userPointsReq : userPointsReqList) {
            //获取zset的score 积分加时间戳
            System.out.println("userPointsReq = " + userPointsReq);
            double scores = userPointsReq.getPoints() + (1 - userPointsReq.getUpdateTime() / 1e13);
            //调用zset的api存储
            this.stringRedisTemplate.opsForZSet().add(userKey, userPointsReq.getUserId(), scores);
        }

        //返回
        return true;
    }

    @GetMapping("/userRankings")
    public List<UserRanking> userRankings(@RequestParam("topN") int topN) {
        //获取userKey的数据对象
        Set<ZSetOperations.TypedTuple<String>> typedTuples = this.stringRedisTemplate.opsForZSet().reverseRangeWithScores(userKey, 0, topN - 1);
        //创建集合
        List<UserRanking> userRankings = new ArrayList<>();
        //遍历数据到一个集合
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            UserRanking userRanking = new UserRanking();

            userRanking.setUserId(typedTuple.getValue());
            userRanking.setRedisScore(typedTuple.getScore());

            userRankings.add(userRanking);
        }

        //返回结果
        return userRankings;
    }
}

